package chances.epg.ui.taglib.html;

import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

import chances.epg.ui.taglib.model.EpgPageContext;
import chances.epg.ui.taglib.model.LinkModel;
import chances.epg.ui.taglib.model.LinkModelRelativeCaculator;
import chances.epg.ui.taglib.model.Widget;

@SuppressWarnings("serial")
public class DirectionTag extends TagSupport {
	private String group;
	private String widget;
	private String var;

	@Override
	public int doEndTag() throws JspException {
		EpgPageContext epgPageContext = (EpgPageContext) pageContext.findAttribute(EpgPageContext.NAME);
		if (epgPageContext != null) {
			List<LinkModel> links = null;
			if (StringUtils.isNotEmpty(this.group)) {
				links = epgPageContext.getLinkGroups().get(group);
			} else if (StringUtils.isNotEmpty(this.widget)) {
				Widget aWidget = epgPageContext.getWidget(widget);
				links = aWidget.getLinks().stream().map(s -> {
					return epgPageContext.findLink(s);
				}).collect(Collectors.toList());

			} else {
				links = epgPageContext.getLinkGroups().get(EpgPageContext.DEFALUT_GROUP);
			}
			if (links != null) {
				if (StringUtils.isEmpty(this.var)) {
					LinkModelRelativeCaculator.caculateFocusRects(links);
				}else{
					this.pageContext.setAttribute(var, links);
				}
			}
		}
		return super.doEndTag();
	}

	public String getGroup() {
		return group;
	}

	public void setGroup(String group) {
		this.group = group;
	}

	public String getWidget() {
		return widget;
	}

	public String getVar() {
		return var;
	}

	public void setWidget(String widget) {
		this.widget = widget;
	}

	public void setVar(String var) {
		this.var = var;
	}

}
